#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author:Zx
@file: auth_utils.py
@time: 2025/7/23  10:49
# @describe:
"""
import logging

from flask_login import LoginManager
from models.user import User
from utils.data_utils import load_users


def init_login_manager(app):
    """初始化登录管理器"""
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'

    @login_manager.user_loader
    def load_user(user_id):
        try:
            users = load_users()
            user_data = next((u for u in users if u['id'] == int(user_id)), None)
            if user_data:
                user_data.setdefault('data_add_records', {})
                return User(user_data)
        except Exception as e:
            logging.error(f"加载用户失败: {e}")
        return None

    return login_manager